# -*- coding:utf-8 -*-

import time
import zipfile

import os

import shutil

from com import MyDevice, App, TimeUtils, LogUtil, BugUtils
from flash_tool.flash import FlashTools
from launch_test import LaunchDataUtils, LaunchData, CmdLuanchTask

CMD_BOOST_SYS = 2
CMD_BOOST_DEMO = 3

# 服务器地址
server_dir = r'\\172.16.1.230\Tiffany\3.dailybuild_release\11.MEIOS_T9_PVT_DailyBuild_8.1'
# 设备序列号
T9_num = 'c5cbc2b9'  # 'c5c3c2e2'  'c4b5c29f' cf47caad
# 是否为调试环境
is_debug = True
# xls html等文件的存放路径
mpath = LaunchData(is_debug)
# 测试次数，至少3次以上，因为要扣掉最大值和最小值
test_count = 2


def launch_test(my_dev, mpath, test_count=2, boost_type=CMD_BOOST_DEMO):
    assert isinstance(mpath, LaunchData)
    assert isinstance(my_dev, MyDevice)

    for i in range(0, test_count):
        LogUtil.i('第' + str(i) + '次测试')
        if boost_type == CMD_BOOST_SYS:
            sys = App.get_sys_apps()
            sys_task = CmdLuanchTask(sys, my_dev, mpath, sheet='sys')
            sys_task.start()
            sys_task.join()
        elif boost_type == CMD_BOOST_DEMO:
            demos = App.get_demo_apps()
            demo_task = CmdLuanchTask(demos, my_dev, mpath, sheet='demo')
            demo_task.start()
            demo_task.join()
    else:
        pass


def exe_test(msg='', day_delta=1):
    LogUtil.i(msg)
    my_dev = MyDevice(T9_num)
    # # 刷机
    # new_rom = FlashTools.get_daily_zip(server_dir, unzip_dir='./daily_rom/', day_delta=day_delta)
    # if new_rom is None:
    #     LogUtil.e('版本异常,当天测试中断！')
    #     return
    # flash_ok = FlashTools.flash_by_py(T9_num, new_rom, save_userdata=True)
    # if not flash_ok:
    #     LogUtil.e('刷机失败！当天测试中断！')
    #     return
    # # 等待开机完毕
    # my_dev.wait_device_ready()
    # time.sleep(10)

    # 开始测试,dev要重新初始化，版本号才会更新
    my_dev = MyDevice(T9_num)
    launch_test(my_dev, mpath, test_count=test_count, boost_type=CMD_BOOST_DEMO)
    launch_test(my_dev, mpath, test_count=test_count, boost_type=CMD_BOOST_SYS)

    # 绘制曲线图并发送报告
    LaunchDataUtils.parse_histroy_data(mpath)


def timer_fun(hour, min):
    exe_time = str(hour) + ':' + str(min)
    import schedule
    schedule.every().day.at(exe_time).do(exe_test, '开始自动化测试！')
    while True:
        schedule.run_pending()
        time.sleep(10)
        LogUtil.i(TimeUtils.format_current_time_ms() + ' wating...')


def cllect_histroy_data(first_version=7):
    for i in range(1, first_version):
        day = first_version - i
        exe_test(day_delta=day)


if __name__ == '__main__':
    # exe_test()
    # timer_fun(8, 00)
    # LaunchDataUtils.parse_histroy_data(mpath)

    dir=mpath.trace_log_dir
    folder_path=r'E:\Python_Proj\AutoTestPy\launch_test\trace_log\Tiffany_36813'

    for file_object in os.listdir(folder_path):
        file_object_path = os.path.join(folder_path, file_object)
        if os.path.isfile(file_object_path):
            os.unlink(file_object_path)
        else:
            shutil.rmtree(file_object_path)
